﻿namespace G27.Web.PerRequestUnityContainer
{
    using System;
    using System.Web;
    using Microsoft.Practices.Unity;

    internal class PerRequestUnityContainerModule : IHttpModule
    {
        private static string CONTEXT_KEY = "UnityContainer";
        private static IUnityContainer _container = new UnityContainer();

        public static IUnityContainer UnityContainer
        {
            get
            {
                IUnityContainer container = HttpContext.Current.Items[CONTEXT_KEY] as IUnityContainer;
                if (container == null)
                {
                    container = _container.CreateChildContainer();
                    HttpContext.Current.Items[CONTEXT_KEY] = container;
                }
                return container;
            }
        }

        public void Init(HttpApplication context)
        {
            context.EndRequest += new EventHandler(HttpContext_EndRequest);
        }

        private void HttpContext_EndRequest(object sender, EventArgs e)
        {
            IUnityContainer container = HttpContext.Current.Items[CONTEXT_KEY] as IUnityContainer;
            if (container != null)
            {
                container.Dispose();
            }
        }

        public void Dispose() {}

    }
}
